<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Created by PhpStorm.
 * User: jz
 * Date: 16/7/21
 * Time: 下午4:28
 */
class Login extends CI_Controller{
    private $LOGIN_ERROR = array(
        'ERROR_LOGIN_CAPTCHA' => 'error_captcha',
        'ERROR_LOGIN_USER_PASSWORD' => 'error_user_password'
    );
    
    
    public function index()
    {
        $this->load->model('admin/login_model');
        
        $captcha = $this->login_model->create_captcha();
        $data['captcha'] = $captcha['image'];
        
        $this->load->view('admin/login.html', $data);
    }
    
    
    
    public function login_doing()
    {
        $this->load->model('admin/login_model');
        $this->load->library('form_validation');
        
        $captcha = $this->input->post('captcha');
        $ret = $this->login_model->is_valid_captcha($captcha);
        if (!$ret){
            echo $this->LOGIN_ERROR['ERROR_LOGIN_CAPTCHA'];
            return;
        }
        
        $email = $this->input->post('email');
        if (!$this->form_validation->valid_email($email)){
            echo $this->LOGIN_ERROR['ERROR_LOGIN_USER_PASSWORD'];
            return;
        }
        
        $password = $this->input->post('password');
        if (!$this->login_model->find($email, $password)){
            echo $this->LOGIN_ERROR['ERROR_LOGIN_USER_PASSWORD'];
            return;
        }
        $session_data = array(
            'email' => $email,
            'login_time' => time()
        );
        
        $this->session->set_userdata($session_data);
        echo base_url('admin/admin.html');
    }
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('admin/login');
    }
}